package com.example.demo.config;


import com.example.demo.entity.DataSource;
import com.example.demo.entity.EsConfig;
import com.example.demo.enums.Constants;
import com.example.demo.service.DatasourceService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.log4j.Log4j2;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Log4j2
@Configuration
public class ElasticSearchConfig {
    @Value("${elasticsearch.url}")
    private String url;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Value("${elasticsearch.scheme}")
    private String scheme;

    @Value("${elasticsearch.username}")
    private String username;

    @Value("${elasticsearch.password}")
    private String password;

    @Autowired
    private DatasourceService datasourceService;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        try {

            log.info("loading ES datasource ...");

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            List<DataSource> dataSource = datasourceService.getAll();
            EsConfig config = new EsConfig(url, port, scheme);
            // 找到type为ES的数据
            dataSource = dataSource.stream().filter(item -> Objects.equals(item.getType(), Constants.DATASOURCE_TYPE_ES.getCode())).collect(Collectors.toList());
            if (!Collections.isEmpty(dataSource)) {
                // { schema:"http", port:92, host:"localhost" }
                ObjectMapper objectMapper = new ObjectMapper();
                config = objectMapper.readValue(dataSource.get(0).getUrl(), EsConfig.class);
            }
            log.info("loaded ES datasource success: {}", dataSource);
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                                    new HttpHost(url, port, scheme))
                            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                    httpClientBuilder.disableAuthCaching();
                                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                                }
                            }));
            return client;

        } catch (Exception e) {
            log.error("loaded ES datasource fail：{}", e);
        }
        return null;
    }
}
